/*
 * @Author: Setsuna
 * @Email: setsuna.xyz@qq.com
 * @FilePath: \src\pages\TodoList\StockCheck\Table\index.tsx
 * @Date: 2021-07-09 11:25:54
 * @LastEditTime: 2023-04-29 00:16:59
 */
import React from 'react'
import TodoTable from '../../component/Table'
import { columnRenders, http, UdDrawer, UdModal } from '@/lib'
import { ETodoTabTypes } from '../../List/configOption'
import apis from '@/apis/AboutQuota'
import InventoryModal from '@/pages/QuotaManage/StockCheck/List/component/InventoryModal'
import StockCheckModal from '@/pages/QuotaManage/StockCheck/QuatoDetail/StockCheckModal'
import StockCheckModalDistributor from '@/pages/QuotaManage/StockCheck/QuatoDetail/StockCheckModalDistributor'
import { message } from 'antd'
export default class StockCheckTable extends TodoTable {
  private refresh = this.props.refresh
  private todoType = this.props.todoType
  constructor(props) {
    super(props)
    let detailAuthId =
      props.stockType === ETodoTabTypes.JXSSTOCKAPPROVAL
        ? 'my_backlog_quota_orgdetail'
        : 'my_backlog_quota_workflowdetail'
    this.state = {
      rowKey: (record, index) => index + '',
      columns: [
        ...this.commonColumns,
        {
          title: '客户类型',
          dataIndex: 'agentType',
          width: 200,
          render: (text, model) => {
            return model.agentType === 1 ? '经销商' : '分销商'
          },
        } as any,
        {
          title: '操作',
          dataIndex: 'operate',
          width: 200,
          render: columnRenders.operate([
            {
              title: '编辑重发',
              show: (text: any, model: any, index: number) => model.approvalStatus === 2 && this.todoType === 3,
              action: (text, model) => this.showImportRecordDetailModal(model),
            },
            { title: '查看详情', auth: detailAuthId, action: (text, model) => this.goDetail(model) },
          ]),
        },
      ],
    }
  }

  componentDidMount(): void {}

  private getDealerCheckStockStatus = (record: any) => {
    let { brandCode, agentCode: dealerCode } = record
    const userName = JSON.parse(sessionStorage.getItem('UaaSysInfo')).profile.username
    let params = {
      userName,
      brandCode,
      dealerCode: Object.is(record.agentType, 2) ? record.parentCode : dealerCode,
    }
    return http
      .get(apis.GetDealerCheckStockStatus, { params })
      .then(res => {
        return res.data.openCheckStock
      })
      .catch(() => {
        return Promise.reject()
      })
  }

  private showImportRecordDetailModal = async (record: any) => {
    
    let openCheckStock = await this.getDealerCheckStockStatus(record)
    if (openCheckStock !== 'Y') {
      message.warn('无盘点权限')
      return
    }
    record['dealerCode'] = record.agentCode
    http
      .get(apis.GetInventoryDateByBrandCode, {
        params: { dealerCode: Object.is(record.agentType, 2) ? record.parentCode : record.dealerCode },
      })
      .then(res => {
        let brandLists = res.data
        //* 只显示当前品牌公司的数据
        brandLists = brandLists.filter(item => item.brandCode === record.brandCode)
        let canOpen = brandLists.every(item => {
          return item.isAllowd === true
        })
        let inventoryBegineTime = brandLists[0]?.inventoryDateMonths[0]?.monthStartTime
        let inventoryEndTime = brandLists[0]?.inventoryDateMonths[0]?.monthEndTime
        if (canOpen) {
          UdModal.open({
            title: '选择在盘点时间范围内的公司',
            width: '45%',
            content: <InventoryModal brandList={brandLists} />,
            onOk: value => {
              Array.isArray(value) &&
                value.length > 0 &&
                this.handStockCheck({
                  value: value[0],
                  record,
                  inventoryBegineTime,
                  inventoryEndTime,
                })
            },
          })
        } else {
          message.warn('未到盘点时间')
        }
      })
  }

  private handStockCheck = ({
    record,
    inventoryBegineTime,
    inventoryEndTime,
    value: { cycleText, brandName, brandCode },
  }) => {
    if (Object.is(record.agentType, 2) && record.parentCode) {
      // 分销商库存盘点
      UdDrawer.open({
        title: `库存盘点`,
        width: '70%',
        content: (
          <StockCheckModalDistributor
            detailDataSource={{
              record,
              agentType: record.agentType,
              tradeCode: record.traceCode,
              cycleText,
              brandName,
              brandCode,
              dealerName: record.dealerName,
              dealerCode: record.dealerCode,
              inventoryBegineTime,
              inventoryEndTime,
            }}
          />
        ),
      })
    } else {
      UdDrawer.open({
        title: `库存盘点`,
        width: '70%',
        content: (
          <StockCheckModal
            todoType={this.props.todoType}
            refresh={this.props.refresh}
            detailDataSource={{
              record,
              agentType: record.agentType,
              tradeCode: record.traceCode,
              cycleText,
              brandName,
              brandCode,
              dealerName: record.agentName,
              dealerCode: record.agentCode,
              inventoryBegineTime,
              inventoryEndTime,
            }}
          />
        ),
      })
    }
  }

  public goDetail = row => {
    const { id, taskDefId, traceCode: businessKey, brandCode } = row
    const { todoType, stockType } = this.props
    this.props.history.push(
      '/todo/stockcheck/detail/' +
        id +
        '?taskId=' +
        taskDefId +
        '&type=' +
        todoType +
        '&businessKey=' +
        businessKey +
        '&brandCode=' +
        brandCode +
        '&stockType=' +
        stockType
    )
  }
}
